package com.example.demo.util;

import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Description: rest请求工具类
 * @author: liyuan
 * @data 2020-11-20 15:52
 */
public class RestRequestUtil {

    /***
     * 得到请求头
     * @param mediaType
     * @return
     */
    public static HttpHeaders getHeader(MediaType mediaType) {
        HttpHeaders headers = new HttpHeaders();
//        headers.put(HttpHeaders.COOKIE, null);
//        headers.put(HttpHeaders.AUTHORIZATION, null);
        headers.setContentType(mediaType);
        return headers;
    }

    /***
     *  发送 Content-Type:application/octet-stream请求，对应postman中的binary请求
     *  可以理解为二进制流的请求
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static HttpEntity octetStreamEntity(InputStream inputStream) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        int len = inputStream.available();
        byte[] byffer = new byte[len];
        inputStream.read(byffer);
        inputStream.close();
        ByteArrayResource resource = new ByteArrayResource(byffer);
        return new HttpEntity(resource, headers);
    }

    /***
     * 类似于form表单的请求体
     * @return
     */
    public static MultiValueMap<String, Object> getEntityByMultiForm() {
        MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<String, Object>();
        return multiValueMap;
    }

    public static HttpEntity getEntity(Object body, HttpHeaders headers) {
        HttpEntity entity = new HttpEntity(body, headers);
        return entity;
    }

    /***
     *  放多个请求内容，类似于form表单的请求
     * @param body
     * @param headers
     * @return
     */
    public static HttpEntity getMultiEntity(LinkedMultiValueMap<String, Object> linkedMultiValueMap, HttpHeaders headers) {
        HttpEntity<MultiValueMap<String, Object>> multiValueMapHttpEntity = new HttpEntity<>(linkedMultiValueMap, headers);
        MultiValueMap<String, Object> multiValueMap = multiValueMapHttpEntity.getBody();
//        multiValueMap.add("", new Object());
//        multiValueMap.put("", new Object());//put不行
        return multiValueMapHttpEntity;
    }


    /***
     *  指定url和方法，请求体(含头和body)的rest请求
     * @param url
     * @param method
     * @param entity
     * @return
     */
    public static String exchange(String url, HttpMethod method, HttpEntity entity) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, method, entity, String.class);
        return responseEntity.getBody();
    }
}
